﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace Benefit.Service.Sys
{
    /// <summary>
    /// 设定交易员可以看到的组
    /// </summary>
    public class ServiceOperatorCouldSeeGroups : Benefit.Interface.Sys.IOperatorCouldSeeGroups
    {
        Benefit.DB.DBManager db = null;
        public ServiceOperatorCouldSeeGroups(Benefit.DB.DBManager db)
        {
            this.db = db;
        }
        public List<Models.Sys.Groups> GetOperatorCouldSeeGroups(int operatorId)
        {
            List<Models.Sys.Groups> groups = new List<Models.Sys.Groups>();
            var query = db.OperatorCouldSeeGroups.Where(a => a.OperatorId == operatorId).Include(a => a.Group).ToList();
            foreach (Models.Sys.OperatorCouldSeeGroups g in query)
            {
                groups.Add(g.Group);
            }
            return groups;
        }
        public void Delete()
        {
            var query = db.OperatorCouldSeeGroups;
            foreach (Models.Sys.OperatorCouldSeeGroups g in query)
            {
                db.OperatorCouldSeeGroups.Remove(g);
            }
            db.SaveChanges();
        }
        /// <summary>
        /// 在每天的小组，组员绑定的时候对他们进行可查看小组的绑定
        /// </summary>
        /// <param name="operatorid"></param>
        /// <param name="groups"></param>
        public void ResetOperatorColuldSeeGroups(int operatorid, int groupid)
        {
            //  Delete(db);
            var query = db.OperatorCouldSeeGroups.Where(a => a.OperatorId == operatorid).Where(a => a.GroupId == groupid);
            if (query.Count() == 0)
            {
                Models.Sys.OperatorCouldSeeGroups s = new Models.Sys.OperatorCouldSeeGroups();
                s.OperatorId = operatorid;
                s.GroupId = groupid;
                db.OperatorCouldSeeGroups.Add(s);
            }
            db.SaveChanges();
        }

        public void InitOperatorCouldSeeGroups()
        {
            Delete();
            var query = db.Groups.ToList();
            foreach (Models.Sys.Groups g in query)
            {
                int gid = g.Id;
                Interface.Sys.IOperator iop = new Sys.ServiceOperator(db);
                var operators = iop.GetUnDeletedOperators();
                foreach (Models.Sys.Operator op in operators)
                {
                    Interface.Sys.IVisitPrower ivp = new Sys.ServiceVisitPrower(db);
                    if (ivp.OperatorHasGroupPrower(op.Id, gid))
                    {
                        ResetOperatorColuldSeeGroups(op.Id, gid);
                    }
                }
            }
            db.SaveChanges();
        }
    }
}
